/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.emex.app.stuff.admin;

import com.emex.app.stuff.security.SecurityManager;
import com.emex.app.shared.data.User;
import com.emex.app.stuff.gui.UserDialog;
import com.emex.app.stuff.gui.model.UserTableModel;
import com.emex.app.stuff.provider.AuthenticationDataProvider;
import java.awt.Frame;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.emex.app.stuff.admin//UserAdministration//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "UserAdministrationTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_NEVER
)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.emex.app.stuff.admin.UserAdministrationTopComponent")
@ActionReference(path = "Menu/Администрирование" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_UserAdministrationAction",
        preferredID = "UserAdministrationTopComponent"
)
@Messages({
    "CTL_UserAdministrationAction=Администрация пользователей",
    "CTL_UserAdministrationTopComponent=Администрация пользователей",
    "HINT_UserAdministrationTopComponent=Администрация пользователей"
})
public final class UserAdministrationTopComponent extends TopComponent {

    private static Frame mainWindow = WindowManager.getDefault().getMainWindow();

    private UserTableModel userTableModel;

    public UserAdministrationTopComponent() {
        initComponents();
        setName(Bundle.CTL_UserAdministrationTopComponent());
        setToolTipText(Bundle.HINT_UserAdministrationTopComponent());
        if (!SecurityManager.getDefault().getCurrentPerson().getIsAdmin()) {
            addNewUserButton.setEnabled(false);
        }
        customInit();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        usersTable = new org.jdesktop.swingx.JXTable();
        buttonsPanel = new javax.swing.JPanel();
        editUserButton = new javax.swing.JButton();
        deleteUserButton = new javax.swing.JButton();
        addNewUserButton = new javax.swing.JButton();

        jScrollPane1.setViewportView(usersTable);

        buttonsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        org.openide.awt.Mnemonics.setLocalizedText(editUserButton, org.openide.util.NbBundle.getMessage(UserAdministrationTopComponent.class, "UserAdministrationTopComponent.editUserButton.text")); // NOI18N
        editUserButton.setEnabled(false);
        editUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editUserButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(deleteUserButton, org.openide.util.NbBundle.getMessage(UserAdministrationTopComponent.class, "UserAdministrationTopComponent.deleteUserButton.text")); // NOI18N
        deleteUserButton.setEnabled(false);
        deleteUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteUserButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(addNewUserButton, org.openide.util.NbBundle.getMessage(UserAdministrationTopComponent.class, "UserAdministrationTopComponent.addNewUserButton.text")); // NOI18N
        addNewUserButton.setToolTipText(org.openide.util.NbBundle.getMessage(UserAdministrationTopComponent.class, "UserAdministrationTopComponent.addNewUserButton.toolTipText")); // NOI18N
        addNewUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addNewUserButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout buttonsPanelLayout = new javax.swing.GroupLayout(buttonsPanel);
        buttonsPanel.setLayout(buttonsPanelLayout);
        buttonsPanelLayout.setHorizontalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addNewUserButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(editUserButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(deleteUserButton)
                .addContainerGap(161, Short.MAX_VALUE))
        );
        buttonsPanelLayout.setVerticalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buttonsPanelLayout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addGroup(buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addNewUserButton)
                    .addComponent(editUserButton)
                    .addComponent(deleteUserButton))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(buttonsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(buttonsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void deleteUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteUserButtonActionPerformed
        User selection = getUserSelection();
        AuthenticationDataProvider.getInstance().deleteUserByPrimaryKey(selection.getId());
        userTableModel.dataRemoved(selection);
    }//GEN-LAST:event_deleteUserButtonActionPerformed

    private void addNewUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addNewUserButtonActionPerformed
        UserDialog dialog = new UserDialog(mainWindow, true);
        dialog.setUserTableModel(userTableModel);
        dialog.setLocationRelativeTo(null);
        dialog.setTitle("Добавить нового пользователя");
        dialog.setVisible(true);
    }//GEN-LAST:event_addNewUserButtonActionPerformed

    private void editUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editUserButtonActionPerformed
        UserDialog dialog = new UserDialog(mainWindow, true);
        dialog.setUser(getUserSelection());
        dialog.setUserTableModel(userTableModel);
        dialog.setLocationRelativeTo(null);
        dialog.setTitle("Редактировать пользователя");
        dialog.setVisible(true);
    }//GEN-LAST:event_editUserButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addNewUserButton;
    private javax.swing.JPanel buttonsPanel;
    private javax.swing.JButton deleteUserButton;
    private javax.swing.JButton editUserButton;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable usersTable;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    protected void customInit() {
        userTableModel = new UserTableModel();
        usersTable.setModel(userTableModel);
        usersTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int row = usersTable.getSelectedRow();
                if ((row >= 0) && (row < usersTable.getRowCount())) {
                    if (SecurityManager.getDefault().getCurrentPerson().getIsAdmin()) {
                        editUserButton.setEnabled(true);
                        deleteUserButton.setEnabled(true);
                    } else {
                        editUserButton.setEnabled(false);
                        deleteUserButton.setEnabled(false);
                    }
                } else {
                    editUserButton.setEnabled(false);
                    deleteUserButton.setEnabled(false);
                }
            }
        });
    }

    protected User getUserSelection() {
        if (usersTable.getSelectedRow() > -1) {
            User user = (User) usersTable
                    .getValueAt(usersTable.getSelectedRow(), -1);
            return user;
        }
        return null;
    }
}
